using BackData;
using Domain;
using Domain.工艺工序;
using Infratructure;
using MediatR;
using Microsoft.Extensions.Logging;
using System;
using System.Transactions;
using Team.API.Applocation.Command.Makesteps;
using Yitter.IdGenerator;

namespace Team.API.Applocation.Hanldler.Makesteps
{
    /// <summary>
    /// 启用/禁用处理器：负责状态切换与审计日志记录
    /// </summary>
    public class ToggleMakestepUseHandler : IRequestHandler<ToggleMakestepUseCommand, APIResult<bool>>
    {
        private readonly IRepository<Makestepmodel> repository;
        private readonly IRepository<Nlogmodel> logRepository;
        private readonly ILogger<ToggleMakestepUseHandler> logger;

        public ToggleMakestepUseHandler(
            IRepository<Makestepmodel> repository,
            IRepository<Nlogmodel> logRepository,
            ILogger<ToggleMakestepUseHandler> logger)
        {
            this.repository = repository;
            this.logRepository = logRepository;
            this.logger = logger;
        }

        public async Task<APIResult<bool>> Handle(ToggleMakestepUseCommand request, CancellationToken cancellationToken)
        {
            var entity = await repository.GetByIdAsync(request.Id);
            if (entity == null || entity.Parentid != 0 || entity.IsDel)
            {
                return APIResult<bool>.Faile("记录不存在或已删除");
            }

            var currentUser = string.IsNullOrWhiteSpace(request.CurrentUserName) ? "系统" : request.CurrentUserName;
            entity.IsUse = request.IsUse;

            var logEntity = new Nlogmodel
            {
                Id = YitIdHelper.NextId(),
                Message = $"{currentUser}{(request.IsUse ? "启用" : "禁用")}工艺工序：{entity.Processname}",
                Category = "Process",
                Otherkey = entity.Id,
                Operatingtime = DateTime.Now,
                Operator = currentUser,
                IsDel = false
            };

            using var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
            try
            {
                var effect = await repository.UpdateAsync(entity);
                if (effect <= 0)
                {
                    logger.LogWarning("[工艺工序-状态] 状态更新失败，操作人：{User}，工序：{Process}", currentUser, entity.Processname);
                    return APIResult<bool>.Faile("状态更新失败");
                }

                var logEffect = await logRepository.AddAsync(logEntity);
                if (logEffect <= 0)
                {
                    logger.LogWarning("[工艺工序-状态] 日志写入失败，操作人：{User}，工序：{Process}", currentUser, entity.Processname);
                    return APIResult<bool>.Faile("状态更新失败：日志写入失败");
                }

                transaction.Complete();
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "[工艺工序-状态] 事务执行异常，操作人：{User}", currentUser);
                throw;
            }

            return APIResult<bool>.Ok(request.IsUse ? "启用成功" : "禁用成功", true);
        }
    }
}

